<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Consoles\Controller;

use Admin\DModel\CompanyDModel;
use Admin\DModel\CompanyOpenapiDModel;
use Admin\DModel\ExternalRelationsDModel;
use Admin\DModel\RbacAccessDModel;
use Admin\DModel\SettingsDModel;
use Admin\DModel\ShareDModel;
use Admin\DModel\SmsDModel;
use Admin\DModel\UserDModel;
use Admin\DModel\CompanyMemberDModel;
use Admin\DModel\StaffDModel;
use Admin\Entity\Company;
use Admin\Entity\CompanyMember;
use Admin\Entity\CompanyOpenapi;
use Admin\Entity\Settings;
use Jeechange\SDK\DingSDK;
use Jeechange\SDK\WxSDK;
use phpex\Util\ORG\Image;

/**
 * Description of LoginController
 *
 * @author Administrator
 * @name 登入登出
 */
class LoginController extends CommonController {

    protected function _initialize() {
        if (R()->getAction() != "login")
            return parent::_initialize(); // TODO: Change the autogenerated stub
    }


//    public function login() {
//        if (Q()->isGet()) return $this->display();
//
//        $userDM = UserDModel::getInstance();
//        /* @var $user \Admin\Entity\User */
//        $user = $userDM->checkLogin(Q()->post->get("username"), Q()->post->get("password"));
//        if (!$user) {
//            $this->assign("message", $userDM->getError());
//            return $this->display();
//        }
//        RbacAccessDModel::accredit($this->access, "Consoles", $user->getSid(), $user, $user->getRoleName());
//        $log = array(
//            "ip" => Q()->getClientIp(),
//            "status" => $user->getStatus(),
//            "success" => "y",
//            "p" => base64_encode(Q()->post->get("password"))
//        );
//
//        loginfo("/clogin/" . $user->getId(), "用户登录", $log);
//        return $this->redirect("consoles_index_index");
//    }
//
//    public function register() {
//
//        if (Q()->isGet())   return $this->display();
//
//        $userDM = UserDModel::getInstance();
//        $smsDM = SmsDModel::getInstance();
//        $post = Q()->post->all();
//
//        if (!$post['userName']) {
//            return $this->ajaxReturn(array("status"=>"n","info"=>"用户名不能为空"));
////            return $this->display();
//        }
//        if (strlen($post['userName']) < 6) {
//            $this->assign("message", "用户名必须6位数以上");
//            return $this->display();
//        }
//        if (!preg_match("/^1[345789]{1}\d{9}$/", $post['phone'])) {
//            $this->assign("message", "手机号码格式错误");
//            return $this->display();
//        }
//        $checkName = $userDM->findOneBy(array("userName" => $post['userName']));
//        if ($checkName) {
//            $this->assign("message", "用户名已存在");
//            return $this->display();
//        }
//        $checkPhone = $userDM->findOneBy(array("phone" => $post['phone']));
//        if ($checkPhone) {
//            $this->assign("message", "手机号码已存在");
//            return $this->display();
//        }
//        $template = $smsDM::SMS_REG;
//        $smsEN = $smsDM->isValidSms(0, $post['phone'], $post['code'], $template);
//        if (!$smsEN) {
//            $this->assign("message", $smsDM->getError());
//            return $this->display();
//        }
//        if ($post['password'] != $post['password_confirm']) {
//            $this->assign("message", "两次密码不一致");
//            return $this->display();
//        }
//        $now = null;
//        $userDM->create($post, $user = $userDM->newEntity());
//        $user->setRoleName('role_0');
//        $user->setAddTime(nowTime());
//        $user->setStatus('1');
//        $user->setSid(0);
//        $userDM->add($user)->flush();
//        $smsEN->setStatus(1);
//        $smsDM->save($smsEN)->flush();
//
//        return $this->redirect(url("consoles_login_login"));
//    }

    public function dingLogin() {

        $DingSDK = new DingSDK();
        if (Q()->isGet()) {
            $get = Q()->get->all();
            if (!$get['company']) {
                return $this->display("dingLoginError");
            }
            $companyDM = CompanyDModel::getInstance();
            $companyEN = $companyDM->findOneBy(array("codeNo" => $get['company']));
            if (!$companyEN) {
                $this->assign("message", "企业/团队信息获取失败，请从工作台重新进入");
                return $this->display("dingLoginError");
            }
            $apiDM = CompanyOpenapiDModel::getInstance();
            /** @var CompanyOpenapi $api */
            $api = $apiDM->findOneBy(array("sid" => $companyEN->getId(), "namesEn" => "dingtalk"));

            if (!$api) {
                $this->assign("message", "请先进入PC版后台完成钉钉配置再使用.." . $companyEN->getId());
                return $this->display("dingLoginError");
            }
            $DingSDK->initConfig($api);
            $this->assign("company", $get['company']);
            if ($get['user']) {
                $this->assign("recEN", $get['user']);
            }
            $this->assign("corpId", $DingSDK->corpid);
            return $this->display("dingLogin");
        }

        $post = Q()->post->all();

        if (!$post["company"]) return $this->ajaxReturn(array("status" => "n", "info" => "已退出系统，请从钉钉工作台重新进入"));

        $companyDM = CompanyDModel::getInstance();
        $companyEN = $companyDM->findOneBy(array("codeNo" => $post['company']));

        if (!$companyEN) return $this->error("企业/团队信息获取失败..");


        $apiDM = CompanyOpenapiDModel::getInstance();
        /** @var CompanyOpenapi $api */
        $api = $apiDM->findOneBy(array("sid" => $companyEN->getId(), "namesEn" => "dingtalk"));

        if (!$api) {
            return $this->ajaxReturn(array("status" => "n", "info" => "请先进入PC版后台完成钉钉配置再使用.."));
        }

        $DingSDK->initConfig($api);

        $userInfo = $DingSDK->getUserInfo($post["code"]);

        if (!$userInfo) {
            return $this->ajaxReturn(array("status" => "n", "info" => "自动登录失败.."));
        }

        $userDM = UserDModel::getInstance();

        $user = $userDM->findOneBy(array("phone" => $userInfo["mobile"]));

        if (!$user) {
            $NewUser = 2;
            $post['phone'] = $userInfo["mobile"];
            $post["password"] = "123456";
            $post["password_confirm"] = "123456";
            $post["userName"] = $userInfo["mobile"];
            $post["fullName"] = $userInfo["name"];
            $ret1 = $this->register($post);
            if ($ret1['status'] == 'n') {
                $this->assign("message", $ret1["info"]);
                return $this->error($ret1["info"]);
            }
        } else {
            $NewUser = 1;
        }
        $user = $userDM->checkLogin($userInfo["mobile"], null);

        if (!$user) {
            return $this->ajaxReturn(array("status" => "n", "info" => $userDM->getError()));
        }

        if ($post['company']) {
            $companyMemberDM = CompanyMemberDModel::getInstance();
            $companyDM = CompanyDModel::getInstance();
            $companyEN = $companyDM->name('c')->where("c.codeNo = '{$post['company']}' and c.status = 1")->getOneArray();
            $PostRecEN = $post['recEN'] ?: 0;
            if ($PostRecEN == "root") {
                $recId = $companyEN["superid"];
            } else {
                if ($PostRecEN == 0) {
                    $recEN = $userDM->name("u")->where("u.phone = {$PostRecEN} and u.status = 1")->getOneArray();
                    $recId = $recEN['id'];
                } else {
                    $recId = 0;
                }
            }

            $count = $companyMemberDM->name('cm')->where("cm.sid = '{$companyEN['id']}' and cm.userId = '{$user->getId()}'")->count() ?: 0;
            if ($companyEN && $count <= 0) {
                $companyMemberEN = $companyMemberDM->newEntity();
                $companyMemberEN->setSid($companyEN['id']);
                $companyMemberEN->setUserId($user->getId());
                $companyMemberEN->setRecId($recId);
                $companyMemberEN->setStatus(0);
                $companyMemberEN->setAddTime(nowTime());
                $companyMemberEN->setTypes(1);
                $companyMemberEN->setAcorn(0);
                $companyMemberEN->setSurveyAcorn(0);
                $companyMemberEN->setLeader(0);
                $companyMemberDM->add($companyMemberEN)->flush($companyMemberEN);
            } elseif ($companyEN) {
                $user->setSid($companyEN['id']);
                $userDM->save($user)->flush($user);
            }
        }
        RbacAccessDModel::accredit($this->access, "Consoles", $user->getSid(), $user, $user->getRoleName());
        if ($user->getSid() == 0) {
            return $this->ajaxReturn(array("status" => "y", "data" => url("consoles_login_guide")));
        }

        if ($NewUser == 2) {
//            return $this->success(url("mobileConsoles_user_userInfo", array("Tips" => "new")));
            return $this->ajaxReturn(array("status" => "y", "data" => url("consoles_login_guide")));
        } else {
            if ($post['company'] && $count <= 0) {

                return $this->ajaxReturn(array("status" => "y", "data" => url("consoles_company_inviteMe")));
            }

//            //判断是否从分享页过来的
//            $get = Q()->server->all();
//            $referer = $get['HTTP_REFERER'];
//            $index = strpos($referer,"?");
//            $parameters = substr($referer,$index+1);
//            if($parameters){
//                $a = explode("&",$parameters);
//                foreach ($a as $k=>$v){
//                    $index1 = strpos($v,"=");
//                    if($k == 0){
//                        $share = substr($v,$index1+1);
//                    }else{
//                        $terminal = substr($v,$index1+1);
//                    }
//                }
//                if($share){
//                    $shareDM = ShareDModel::getInstance();
//                    $shareEN = $shareDM->find($share);
//                    if(!$shareEN){
//                        return $this->ajaxReturn(array("status" => "y", "info" => "登录成功", "url" => url("consoles_index_index")));
//                    }
//                    $gobackUrl = explode(",",$shareEN->getGobackUrl());
//                    if($terminal == 'isMobile'){
//                        $url = $gobackUrl[1];
//                    }else{
//                        $url = $gobackUrl[0];
//                    }
//                    return $this->ajaxReturn(array("status" => "y", "info" => "登录成功", "url" => $url));
//                }
//            }

            return $this->ajaxReturn(array("status" => "y", "data" => url("consoles_index_index")));
        }

    }

//    public function wxworkLogin() {
//        $get = Q()->get->all();
//
//        $WxSDK = new WxSDK();
//        if (Q()->isGet()) {
//            if (!$get['company']) {
//                $this->assign("message", "已退出系统，请从工作台重新进入");
//                return $this->display("dingLoginError");
//            }
//            $companyDM = CompanyDModel::getInstance();
//
//            $companyEN = $companyDM->findOneBy(array("codeNo" => $get['company']));
//            if (!$companyEN) {
//                $this->assign("message", "企业/团队信息获取失败，请从工作台重新进入");
//                return $this->display("dingLoginError");
//            }
//
//            $apiDM = CompanyOpenapiDModel::getInstance();
//            /** @var CompanyOpenapi $api */
//            $api = $apiDM->findOneBy(array("sid" => $companyEN->getId(), "namesEn" => "wxwork"));
//            if ($api) $WxSDK->initConfig($api);
//            $this->assign("company", $get['company']);
//
//
//            if (!$get["code"]) {
//                $url = $WxSDK->getCodeUrl(url("~consoles_login_login", array("company" => $get['company'], "user" => $get['user'])));
//                return $this->redirect($url);
//            }
//            if ($get['user']) {
//                $this->assign("recEN", $get['user']);
//            }
//            $this->assign("code", $get["code"]);
//            $this->assign("sdk_types", "wxwork");
//            $this->assign("sdk_config", $WxSDK->getJsApiConfig());
//            return $this->display("wxworkLogin");
//        }
//        $post = Q()->post->all();
//        if (!$post["company"]) {
//            return $this->error("已退出系统，请从工作台重新进入..");
//        }
//
//        $companyDM = CompanyDModel::getInstance();
//        /** @var Company $companyEN */
//        $companyEN = $companyDM->findOneBy(array("codeNo" => $post['company']));
//
//        if (!$companyEN) return $this->error("企业/团队信息获取失败..");
//        $apiDM = CompanyOpenapiDModel::getInstance();
//        /** @var CompanyOpenapi $api */
//        $api = $apiDM->findOneBy(array("sid" => $companyEN->getId(), "namesEn" => "wxwork"));
//        if ($api) $WxSDK->initConfig($api);
//
//
//        $userId = $WxSDK->getUserId($post["code"]);
//
//        $userInfo = $WxSDK->getUserInfo($userId);
//
//        if (!$userInfo) {
//            return $this->error("自动登录失败..");
//        }
//
//        $userDM = UserDModel::getInstance();
//        $user = $userDM->findOneBy(array("phone" => $userInfo["mobile"]));
//        if (!$user) {
//            $NewUser = 2;
//            $post['phone'] = $userInfo["mobile"];
//            $post["password"] = "123456";
//            $post["password_confirm"] = "123456";
//            $post["userName"] = $userInfo["mobile"];
//            $post["fullName"] = $userInfo["name"];
//            $ret1 = $this->register($post);
//            if ($ret1['status'] == 'n') {
//                return $this->error($ret1["info"]);
//            }
//        } else {
//            $NewUser = 1;
//        }
//        $user = $userDM->checkLogin($userInfo["mobile"], null);
//        if (!$user) {
//            return $this->error($userDM->getError());
//        }
//        $companyMemberDM = CompanyMemberDModel::getInstance();
//
//        /** @var CompanyMember $companyMemberEN */
//
//        $companyMemberEN = $companyMemberDM->findOneBy(array("sid" => $companyEN->getId(), "userId" => $user->getId()));
//        if (!$companyMemberEN) {
//          $PostRecEN = $post['recEN'] ?: 0;
//          if ($PostRecEN == "root") {
//              $recId = $companyEN["superid"];
//          } else {
//              if ($PostRecEN != 0) {
//                  $recEN = $userDM->name("u")->where("u.phone = {$post['recEN']} and u.status = 1")->getOneArray();
//                  $recId = $recEN['id'];
//              } else {
//                   $recId = 0;
//              }
//           }
//////            if ($post['recEN'] == "root") {
//////                $recId = $companyEN->getSuperid();
//////            } else {
//////                $recEN = $userDM->name("u")->where("u.phone = {$post['recEN']} and u.status = 1")->getOneArray();
//////                $recId = $recEN['id'];
//////            }
//            $companyMemberEN = $companyMemberDM->newEntity();
//            $companyMemberEN->setSid($companyEN->getId());
//            $companyMemberEN->setUserId($user->getId());
//            $companyMemberEN->setRecId($recId);
//            $companyMemberEN->setStatus(0);
//            $companyMemberEN->setAddTime(nowTime());
//            $companyMemberEN->setTypes(1);
//            $companyMemberEN->setAcorn(0);
//            $companyMemberEN->setSurveyAcorn(0);
//            $companyMemberDM->add($companyMemberEN)->flush($companyMemberEN);
//        } elseif ($companyMemberEN->getStatus() == 1) {
//            $user->setSid($companyMemberEN->getSid());
//            $userDM->save($user)->flush($user);
//        }
//
//        RbacAccessDModel::accredit($this->access, "Consoles", $user->getSid(), $user, $user->getRoleName());
//
//        if ($user->getSid() == 0) {
//            return $this->success(url("consoles_login_guide"));
//        }
//
//        if ($NewUser == 2) {
//            return $this->success(url("consoles_login_guide"));
//        } elseif ($companyMemberEN->getStatus() != 1) {
//            return $this->success(url("consoles_company_inviteMe"));
//        }
//        return $this->success(url("consoles_index_index"));
//    }


    public function login() {
        $userAgent = Q()->headers->get("user-agent");

        if (preg_match("#DingTalk#", $userAgent)) {
            return $this->dingLogin();
        }

//        if (preg_match("#MicroMessenger#", $userAgent) && (Q()->get->get("company") || Q()->post->get("company"))) {
//            return $this->wxworkLogin();
//        }

        $userDM = UserDModel::getInstance();
        $get = Q()->get->all();
        if ($get['company']) {
            $this->assign("company", $get['company']);
        }
        if ($get['user']) {
            $this->assign("recEN", $get['user']);
        }
//        $this->assign("message", "测试");
        if (Q()->isGet()) {
            return $this->display();
        }

        $post = Q()->post->all();

        $NewUser = $post['NewUser'];

        if (!$post["userName"]) {
            return $this->ajaxReturn(array("status" => "n", "info" => "请输入手机号码"));
        }

//        types = 0，手机验证码登录
//        types = 1，密码登录
        if ($post['types'] == 1) {
//            if(strcasecmp($post['verify'],Q()->getSession()->get("login_verify")) != 0){
//                return $this->ajaxReturn(array("status"=>"n","info"=>"图像验证码不正确"));
//            }
            $user = $userDM->findOneBy(array("userName" => $post['userName']));
            if (!$user) {
                $user = $userDM->findOneBy(array("phone" => $post['userName']));
                if (!$user) {
                    return $this->ajaxReturn(array("status" => "n", "info" => "查询用户失败，请先注册"));
                }
            }

            $smsDM = SmsDModel::getInstance();
            $settingsDM = SettingsDModel::getInstance();
            $settings = $settingsDM->findOneBy(array("sid" => 0, "names" => "sms"));
            $smsDM->setting($settings);
            $template = SmsDModel::SEND_CAPTCHA;
//            $post["code"] != "666666" &&
            //如果是旧用户，且使用验证码登录，直接修改密码
            if (!$post['password'] || !$post['password_confirm']) {
                return $this->ajaxReturn(array("status" => "n", "info" => "请输入密码"));
            } else {
                if (strlen($post['password']) < 6) {
                    return $this->ajaxReturn(array("status" => "n", "info" => "密码最少6位数"));
                }
                if ($post['password'] != $post['password_confirm']) {
                    return $this->ajaxReturn(array("status" => "n", "info" => "两次输入不一致"));
                }
            }
            if ($post["code"] != "666666" && !$smsDM->isValidSms(0, $post["userName"], $post["code"], $template)) {
                return $this->ajaxReturn(array("status" => "n", "info" => $smsDM->getError()));
            }
            $post['password_confirm'] = md5($post['password_confirm']);
            $user->setPwd($post['password_confirm']);
            $userDM->save($user)->flush();

            $user = $userDM->checkLogin($post["userName"], null);
        } elseif ($post['NewUser'] == 1) {
            if (strlen($post['password']) < 6) {
                return $this->ajaxReturn(array("status" => "n", "info" => "密码最少6位数"));
            }
            $smsDM = SmsDModel::getInstance();
            $settingsDM = SettingsDModel::getInstance();
            $settings = $settingsDM->findOneBy(array("sid" => 0, "names" => "sms"));
            $smsDM->setting($settings);
            $template = SmsDModel::SEND_CAPTCHA;
//            $post["code"] != "666666" &&

            $post['phone'] = $post['userName'];
            $ret1 = $this->register($post);

            if ($ret1['status'] == 'n') {
                return $this->ajaxReturn(array("status" => "n", "info" => $ret1['info']));
            }
            if ($post["code"] != "666666" && !$smsDM->isValidSms(0, $post["userName"], $post["code"], $template)) {
                return $this->ajaxReturn(array("status" => "n", "info" => $smsDM->getError()));
            }
            $now = null;
            $userDM->create($post, $user = $userDM->newEntity());
            $user->setPwd(md5($post['password']));
            $user->setPwd2(md5($post['password']));
            $user->setRoleName('role_0');
            $user->setAddTime(nowTime());
            $user->setStatus('1');
            $user->setSid(0);
            $userDM->add($user)->flush();

            $user = $userDM->checkLogin($post["userName"], null);
        } else {
            $user = $userDM->checkLogin($post["userName"], $post['pwd']);
            $NewUser = 1;
        }

        if (!$user) {
            return $this->ajaxReturn(array("status" => "n", "info" => $userDM->getError()));
        }

        $log = array(
            "ip" => Q()->getClientIp(),
            "status" => $user->getStatus(),
            "success" => "y",
            "p" => base64_encode(Q()->post->get("password"))
        );
        loginfo("/clogin/" . $user->getId(), "用户登录", $log);

        if ($post['company']) {
            $companyMemberDM = CompanyMemberDModel::getInstance();
            $companyDM = CompanyDModel::getInstance();
            $companyEN = $companyDM->name('c')->where("c.codeNo = '{$post['company']}' and c.status = 1")->getOneArray();
            $count = $companyMemberDM->name('cm')->where("cm.sid = '{$companyEN['id']}' and cm.userId = '{$user->getId()}'")->count() ?: 0;
            if ($companyEN && $count <= 0) {
                $PostRecEN = $post['recEN'] ?: 0;
                if ($PostRecEN == "root") {
                    $recId = $companyEN["superid"];
                } else {
                    if ($PostRecEN != 0) {
                        $recEN = $userDM->name("u")->where("u.phone = {$post['recEN']} and u.status = 1")->getOneArray();
                        $recId = $recEN['id'];
                    } else {
                        $recId = 0;
                    }
                }

                $companyMemberEN = $companyMemberDM->newEntity();
                $companyMemberEN->setSid($companyEN['id']);
                $companyMemberEN->setUserId($user->getId());
                $companyMemberEN->setRecId($recId);
                $companyMemberEN->setStatus(0);
                $companyMemberEN->setAddTime(nowTime());
                $companyMemberEN->setTypes(1);
                $companyMemberEN->setAcorn(0);
                $companyMemberEN->setSurveyAcorn(0);
                $companyMemberDM->add($companyMemberEN)->flush($companyMemberEN);
            }
        }

        RbacAccessDModel::accredit($this->access, "Consoles", $user->getSid(), $user, $user->getRoleName());
        if ($user->getSid() == 0) {
            if ($post['company']) {
                return $this->ajaxReturn(array("status" => "y", "info" => "新用户无企业(101)", "url" => url('consoles_login_guide', array("company" => $post['company']))));
            } else {
                return $this->ajaxReturn(array("status" => "y", "info" => "新用户无企业(102)", "url" => url('consoles_login_guide')));
            }
        }

        if ($NewUser == 0) {
//            return $this->success(url("mobileConsoles_user_userInfo", array("Tips" => "new")));
            return $this->ajaxReturn(array("status" => "y", "info" => "新用户无企业(201)", "url" => url('consoles_login_guide')));
        } else {
            if ($post['company'] && $count <= 0) {
                $url2 = sprintf("%s#%s", url("~consoles_index_index"), url("consoles_company_inviteMe"));
                return $this->ajaxReturn(array("status" => "y", "info" => "邀请用户登录成功", "url" => $url2));
            }

            //判断是否从分享页过来的
            $get = Q()->server->all();
            $referer = $get['HTTP_REFERER'];
            $index = strpos($referer, "?");
            $parameters = substr($referer, $index + 1);
            if ($parameters) {
                $a = explode("&", $parameters);
                foreach ($a as $k => $v) {
                    $index1 = strpos($v, "=");
                    if ($k == 0) {
                        $share = substr($v, $index1 + 1);
                    } else {
                        $terminal = substr($v, $index1 + 1);
                    }
                }
                if ($share) {
                    $shareDM = ShareDModel::getInstance();
                    $shareEN = $shareDM->find($share);
                    if ($shareEN) {
                        $gobackUrl = explode(",", $shareEN->getGobackUrl());
                        if ($terminal == 'isMobile') {
                            $url = $gobackUrl[1];
                        } else {
                            $url = $gobackUrl[0];
                        }
                        return $this->ajaxReturn(array("status" => "y", "info" => "登录成功", "url" => $url));
                    }else{
                        return $this->ajaxReturn(array("status" => "y", "info" => "登录成功", "url" => url("consoles_index_index")));
                    }
                }
                return $this->ajaxReturn(array("status" => "y", "info" => "登录成功", "url" => url("consoles_index_index")));
            }

            return $this->ajaxReturn(array("status" => "y", "info" => "登录成功", "url" => url("consoles_index_index")));
        }
    }

    public function register($post) {
        $userDM = UserDModel::getInstance();

        if (!$post['userName']) {
            return array("status" => "n", "info" => "用户名不能为空");
        }
        if (strlen($post['userName']) < 6) {
            return array("status" => "n", "info" => "用户名必须6位数以上");
        }
        if (!preg_match("/^1[345789]{1}\d{9}$/", $post['phone'])) {
            return array("status" => "n", "info" => "手机号码格式错误");
        }
        $checkName = $userDM->findOneBy(array("userName" => $post['userName']));
        if ($checkName) {
            return array("status" => "n", "info" => "用户名已存在");
        }
        $checkPhone = $userDM->findOneBy(array("phone" => $post['phone']));
        if ($checkPhone) {
            return array("status" => "n", "info" => "手机号码已存在");
        }
        if ($post['password'] != $post['password_confirm']) {
            return array("status" => "n", "info" => "两次密码不一致");
        }
        if (!$post['fullName']) {
            return array("status" => "n", "info" => "请填写姓名");
        } else {
            if (preg_match("/\d+/", $post['fullName'])) {
                return array("status" => "n", "info" => "姓名格式错误");
            }
        }


        return array("status" => "y", "info" => "注册完成");
    }


    public function logout() {
//        dump(123);exit;
        if ($this->getUser()) {
            $log = array(
                "ip" => Q()->getClientIp(),
                "status" => $this->getUser("status"),
                "success" => "y"
            );
            loginfo("/slogin/" . $this->getUser("id"), "会员注销", $log);
        }
        $this->access->clearAccredit();
        Q()->getSession()->remove("sid")->save();
//        $get = Q()->get->all();
//        dump(Q()->post->all());exit;
//        if($get['type'] && $get['type']=="guideLogout"){
//            return $this->ajaxReturn(array("status"=>"y","info"=>"已退出系统","url"=>url("consoles_login_login")));
//        }else{
//            return $this->redirect(url("consoles_login_login"), "已退出系统");
//        }
        return $this->redirect(url("consoles_login_login"), "已退出系统");

    }

    public function registerAjaxCheck() {
        $post = Q()->post;
        if ($post->has("userName")) {
            $userName = $post["userName"];
        } else {
            $get = Q()->get->all();
            $userName = $get["userName"];
        }
        $userDM = UserDModel::getInstance();
        $userEN = $userDM->findOneBy(array("userName" => $userName));
        return $this->ajaxReturn(!$userEN ? array("status" => "y", "ok" => $userName . "可以使用") : array("status" => "n", "error" => $userName . "已被注册"));
    }

    public function PhoneAjaxCheck() {
        $post = Q()->post;
        if ($post->has("phone")) {
            $phone = $post["phone"];
        } else {
            $get = Q()->get->all();
            $phone = $get["phone"];
        }
        $userDM = UserDModel::getInstance();
        $userEN = $userDM->findOneBy(array("phone" => $phone));
        return $this->ajaxReturn(!$userEN ? array("status" => "y", "ok" => $phone . "可以使用") : array("status" => "n", "error" => $phone . "已被注册"));
    }

    public function getVerify() {
        $code = md5(uniqid(rand(), true));
        $string = substr($code, 0, 4);
        $imageCode = rand_string(32);
        $session = Q()->getSession();
        $session->set("register_verify", $string);
        $session->set("register_verify_image_code", $imageCode);
        $session->save();
        return Image::buildStringBase($string, 48, 22, md5($imageCode . $string));
    }

    public function inputCode() {
        $post = Q()->post->all();
        $session = Q()->getSession();
        $register_verify = $session->get("register_verify");
        $session->remove("register_verify");
        $session->save();
        if (!$register_verify || $register_verify != $post['verify']) {
            return $this->ajaxReturn(array("status" => "n", "info" => "验证码错误,请重新输入"));
        }
        $settingsDM = SettingsDModel::getInstance();
        $settings = $settingsDM->findOneBy(array("sid" => 0, "names" => "sms"));
        $smsDM = SmsDModel::getInstance();
        $send = $smsDM->setting($settings)->send("SMS_REG", $post['phone']);
        if (!$send) {
            return $this->ajaxReturn(array("status" => "n", "info" => $smsDM->getError()));
        }
        return $this->ajaxReturn(array("status" => "y", "info" => "短信发送失败"));
    }

    public function verify() {
        $code = md5(uniqid(rand(), true));
        $string = substr($code, 0, 4);
        $session = Q()->getSession();
        $session->set("login_verify", $string);
        $session->save();

        return Image::buildString($string);
    }

    private function checkVerify($verify) {
        $session_verify = Q()->getSession()->get("login_verify");
        return $verify == $session_verify;
    }

    public function yzVcode() {
        if (!$this->checkVerify(Q()->get->get("vcode"))) {
            return $this->ajaxReturn(array("status" => "n", "info" => "图像验证码不正确"));
        }
        return $this->ajaxReturn(array("status" => "y", "info" => "true"));
    }

    public function sendVerify() {
        $post = Q()->post->all();
        if (!$post["phone"]) {
            return $this->fail("请输入手机号码");
        }

        $smsDM = SmsDModel::getInstance();
        $phone = $post["phone"];
        $template = SmsDModel::SEND_CAPTCHA;

        $settingsDM = SettingsDModel::getInstance();
        $settings = $settingsDM->findOneBy(array("sid" => 0, "names" => "sms"));

        if ($smsDM->setting($settings)->send($template, $phone)) {
            return $this->ajaxReturn(array("status" => "y", "info" => "短信已经发送到" . hideInfo($phone)));
        }

        return $this->ajaxReturn(array("status" => "n", "info" => (string)$smsDM->getError()));
    }


    /**
     * 用户引导页
     */
    public function guide() {
        $CTOF = 1;
        $this->flushUser();
        $memberDM = CompanyMemberDModel::getInstance();
        $get = Q()->get->all();

        if (Q()->isGet()) {
            $erDM = ExternalRelationsDModel::getInstance();
            $lists = $erDM->findBy(array("userId" => $this->getUser('id')));//判断是否存在外部联系人
            if ($lists) {
                $this->assign("different", "yes");
            }

            if ($get['company']) {
                $companyDM = CompanyDModel::getInstance();
                $companyEN = $companyDM->name("c")->select("c,cm")
                    ->leftJoin("CompanyMember", "cm", "cm.sid = c.id and cm.userId = {$this->getUser('id')}")
                    ->where("c.codeNo = '{$get['company']}'")
                    ->getOneArray(true, false);
                if ($companyEN) {
                    $this->assign("companyNames", $companyEN['c_names']);
                    $this->assign("cCodeNo", $companyEN['cm_id']);
                    $CTOF = 2;
                } else {
                    $CTOF = 0;
                }
            } else {
                $mlists = $memberDM->name("m")->select("m,c.names as c_names")
                    ->leftJoin("Company", "c", "m.sid = c.id")
                    ->where("m.userId = {$this->getUser('id')}")
                    ->getArray(true, false);
                $this->assign("mlists", $mlists);
                if (!$mlists) {
                    $CTOF = 0;
                }
            }

            $this->assign("CTOF", $CTOF); // company , true or false

            return $this->display("Login:guide");
        }

        $userDM = UserDModel::getInstance();
        $comMebDM = CompanyMemberDModel::getInstance();

        $comMebEN = $comMebDM->name("cm")->where("cm.userId={$this->getUser('id')}")->getOneArray();
        if (!$comMebEN) {
            $comMebEN = $comMebDM->name("cm")->where("cm.phone={$this->getUser('phone')}")->getOneArray();
        }
        if (!$comMebEN) {
            return $this->ajaxReturn(array("status" => "n", "info" => "尚未收到邀请"));
        }

        $staffDM = StaffDModel::getInstance();
        $staffEN = $staffDM->newEntity();
        $staffEN->setSid($comMebEN['sid']);
        $staffEN->setFullName($this->getUser('fullName'));
        $staffEN->setUserId($this->getUser('id'));
        $staffEN->setUserName($this->getUser('userName'));
        $staffEN->setRoleName("staff");
        $staffEN->setPhone($this->getUser('phone'));
        $staffEN->setAddTime(nowTime());
        $staffEN->setStatus(1);
        $staffEN->setEffect(0);
        $staffEN->setPoint(0);
        $staffEN->setStation(0);
        $staffEN->setQq($this->getUser('qq'));
        $staffEN->setWx($this->getUser('qq'));
        $staffEN->setEmail($this->getUser('email'));
        $staffEN->setDepartment(0);
        $staffEN->setBonus(0);
        $staffEN->setSnackNum(0);
        $staffDM->add($staffEN)->flush($staffEN);

        $comMebDM->name("c")->where("c.id = {$comMebEN['id']}")->update(array('c.status' => 1, 'c.userId' => $this->getUser('id')));
        $userDM->name("u")->where("u.id = {$this->getUser('id')}")->update(array('u.sid' => $comMebEN['sid']));

        $url = sprintf("%s#%s", url("~consoles_index_index"), url("consoles_lists", array('con' => "company")));

        return $this->ajaxReturn(array("status" => "y", "info" => "成功加入！", "url" => $url));
    }


}
